<template>
  <!-- 商品列表 -->
  <div class="sort-list-container">
    <ul>
      <li v-for="good in goodList" :key="good.id">
        <GoodsItem :goods="good" />
      </li>
    </ul>
  </div>
  <XtxInfiniteLoad
    @load="loadNextList"
    :isFinished="isFinished"
    :isLoading="isLoading"
  />
</template>
<script>
import { findSubCategoryGoods } from '@/api/category'
import { useRoute } from 'vue-router'
import { ref, inject, watch } from 'vue'

import GoodsItem from './goods-item.vue'
export default {
  components: {
    GoodsItem
  },
  setup () {
    // 获取list
    const goodList = ref([])
    const route = useRoute()

    // 加载更多功能
    const isFinished = ref(false) // 是否全部加载完毕
    const isLoading = ref(false)

    // 请求参数
    const reqParams = {
      page: 0,
      pageSize: 20,
      categoryId: route.params.id,
      sortField: null, // 排序类别
      attrs: [], // 商品属性
      brandId: null // 品牌名称
    }

    // 获取过滤条件数据
    const filterParams = inject('filterParams')
    // 监控筛选条件变化，重新刷新列表
    watch(() => filterParams.value, (newVal) => {
      console.log('条件变化：', newVal)
      // 刷新列表
      // 重置列表状态
      goodList.value = []
      reqParams.page = 0
      isFinished.value = false
      // 数据重置之后，最下边的无限加载组件进入可视区域，会触发load事件发请求
      // 合并条件
      // const newParmas = { ...reqParams, ...newVal }
      // loadData(newParmas)
    }, { deep: true })

    async function loadData (reqParams) {
      const res = await findSubCategoryGoods(reqParams)
      goodList.value = res.result.items
    }

    // 加载更多=>进入可视区域默认加载一次
    async function loadNextList () {
      console.log('重置刷新列表', filterParams.value)
      // 开启loading
      isLoading.value = true
      reqParams.page++
      const res = await findSubCategoryGoods({ ...reqParams, ...filterParams.value })
      const newList = res.result.items
      // 追加列表数据
      goodList.value.push(...newList)
      // 关闭loading
      isLoading.value = false
      if (res.result.counts === goodList.value.length) {
        // 列表加载完毕
        isFinished.value = true
      }
    }

    // onMounted(() => {
    //   loadData(reqParams)
    // })
    return {
      goodList,
      isFinished,
      isLoading,
      loadNextList
    }
  }
}
</script>
<style lang="less" scoped>
.sort-list-container {
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
